package org.contextinferenceengine.location;

import java.io.IOException;

import org.contextinferenceengine.DatabaseHelper;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

public class LocationTrackingService extends Service {

	private static boolean isAnInstanceRunning = false;
	private DatabaseHelper dbHelper;
	private Geocoder geocoder; 
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		this.geocoder = new Geocoder(this);

		dbHelper = new DatabaseHelper(this);
		
		// Acquire a reference to the system Location Manager
		LocationManager locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// Define a listener that responds to location updates
		LocationListener locationListener = new LocationListener() {
			public void onLocationChanged(Location location) {

				// Called when a new location is found by the network location
				// provider.

				reactToNewLocation(location);
			}

			public void onProviderEnabled(String provider) {
			}

			public void onProviderDisabled(String provider) {
			}

			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				// TODO Auto-generated method stub

			}
		};

		// Register the listener with the Location Manager to receive location
		// updates
		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 5000*60, 0, locationListener);
		
		
		locationManager.requestLocationUpdates(
				LocationManager.GPS_PROVIDER, 5000*60, 0, locationListener);
		
		
		
		
	}

	private void reactToNewLocation(Location location) {
		this.saveLocationToInferenceDB(location);
	}

	private void saveLocationToInferenceDB(Location location) {
		double lat = location.getLatitude();
		double lon = location.getLongitude();
		double alt = location.getAltitude();
		long time = location.getTime();
		float accuracy = location.getAccuracy();
		String provider = location.getProvider();
		
		
		String addressLine = "unknown address";
		try {
			Address a = geocoder.getFromLocation(lat, lon, 1).get(0);
			addressLine = a.getAddressLine(0);
		} catch (IOException e) {

			e.printStackTrace();
		}
		
		this.dbHelper.insertLocation(time, lat, lon, alt, accuracy, provider, addressLine);

	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		isAnInstanceRunning = true;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		isAnInstanceRunning = false;
	}
	
	public static boolean isAnInstanceRunning(){
		return isAnInstanceRunning;
	}
}
